#coding=utf-8
#LightCam 进程关闭程序

import multiprocessing,subprocess
import socket,os,time,re,sys
import lc_libs

if __name__ == "__main__":

	length = len(sys.argv)
	if length<2:
		strs="wrong para,please input a para."
		print strs
		exit(0)

	agent_hostname=lc_libs.lc_gethostname()

	CurrentConf=[]
	
	for line in open("../conf/lc_status.conf"):
		if line[0] == '#' or line.split("\t")[0] not in (agent_hostname,'default'):
			continue
		CurrentConf.append(line)

	tag=0
	
	for line in CurrentConf:
		ProcessName = line.strip('\n\r').split('\t')[1]
		ScriptsName = line.strip('\n\r').split('\t')[2]
		if ProcessName in sys.argv:
			print "Stoping "+ProcessName + ' ...'
			GetProID="ps -ef|grep -w '"+str(ScriptsName)+"'|grep -v 'grep'|awk '{print $2}'"
			popen=subprocess.Popen(GetProID,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
			while True:
				if popen.poll()==None:
					time.sleep(0.01)
					continue
				else:
					break
			ProID=popen.stdout.read()
			for PID in ProID.split('\n'):
				if PID =='':
					continue
				KillProID="kill -9 "+PID
				#print KillProID
				popen=subprocess.Popen(KillProID,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
				#out=popen.stdout.read()
				#os.system(KillProID)
				time.sleep(0.1)
			print ProcessName + ' has been stoped.'
			tag=1
		elif sys.argv[1] == "All":
			print "Stoping "+ProcessName + ' ...'
			GetProID="ps -ef|grep -w '"+str(ScriptsName)+"'|grep -v 'grep'|awk '{print $2}'"
			popen=subprocess.Popen(GetProID,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
			while True:
				if popen.poll()==None:
					time.sleep(0.01)
					continue
				else:
					break
			ProID=popen.stdout.read()
			for PID in ProID.split('\n'):
				if PID =='':
					continue
				KillProID="kill -9 "+PID
				#print KillProID
				popen=subprocess.Popen(KillProID,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
				#out=popen.stdout.read()
				#os.system(KillProID)
				time.sleep(0.1)
			print ProcessName + ' has been stoped.'
			tag=1
			
	if tag==0:
		print "Nothing to do. Exiting..."
		
		
		
		#cd $LIGHTCAM_HOME/scripts;nohup LightCamPy lc_agent.py > /dev/null &
